package timing.ukulele.storage.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import timing.ukulele.storage.entity.UserEntity;
import timing.ukulele.storage.repository.UserRepository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

@Component("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    @Autowired
    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // 1. 查询用户
        UserEntity filter = new UserEntity();
        filter.setAccount(account);
        filter.setActive(Boolean.TRUE);
        filter.setRole(null);
        Optional<UserEntity> optional = userRepository.findOne(Example.of(filter));
        if (!optional.isPresent())
            return null;
        UserEntity userFromDatabase = optional.get();

        // 2. 设置角色
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(userFromDatabase.getRole());
        grantedAuthorities.add(grantedAuthority);

        return new org.springframework.security.core.userdetails.User(account,
                userFromDatabase.getPassword(), grantedAuthorities);
    }

}